package com.morningstar.common.utils.crypto;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.StandardCharsets;
import java.security.*;

/**
 * SHA 256 工具类
 * @author yls
 */
public class SHA256Crypto {

    /**
     * 日志
     */
    private static final Logger logger = LoggerFactory.getLogger(SHA256Crypto.class);

    /**
     * 生成签名
     * @param content       内容
     * @return              生成的签名
     */
    public static String getSHA256Str(String content) {
        MessageDigest messageDigest;
        String encodeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(content.getBytes(StandardCharsets.UTF_8));
            encodeStr = byte2Hex(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
           logger.error(ExceptionUtils.getStackTrace(e));
        }
        return encodeStr;
    }

    /**
     * 校验签名
     * @param bytes          签名
     * @return               true 签名正确 false 签名错误
     */
    private static String byte2Hex(byte[] bytes) {
        StringBuilder stringBuffer = new StringBuilder();
        String temp = null;
        for (int i=0; i<bytes.length; i++){
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length()==1){
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }

    public static void main (String[] args) {
        logger.info(getSHA256Str("yanglianshan"));
    }
}
